# -*- coding: utf-8 -*-

from SCons.Script import *
import os.path

def configureEnv(**kw):
    env = Environment(tools = ['ppe-elf'], toolpath = [os.path.dirname(__file__)])

    if kw['target'] == 'cell':
        env['_TOOLCHAINPREFIX'] = 'powerpc64-unknown-linux-gnu-'
    elif kw['target'] == 'cell-ps3':
        env['_TOOLCHAINPREFIX'] = ''
    else:
        assert False

    env['CPPFLAGS'] = [
        '-x', 'c++',
        '-Wall',
        '-Woverloaded-virtual',
        '-Wextra',
        '-Wshadow',
        '-Wcast-align',
        '-Wcast-qual',
        '-Winline',
        '-Wno-long-long',
        '-g',
        '-maltivec',
    ]
    if kw['configuration'] == 'debug':
        env['CPPFLAGS'] += [
            '-O0',
        ]
    else:
        env['CPPFLAGS'] += [
            '-O3',
        ]
    env['CPPDEFINES'] = [
        '__PPU__',
    ]

    env.Append(**kw)
    return env

def configureSpeEnv(**kw):
    env = Environment(tools = ['spe-elf'], toolpath = [os.path.dirname(__file__)])

    if kw['target'] == 'cell':
        env['_TOOLCHAINSPUPREFIX'] = 'spu-elf-'
        env['EMBEDSPUCOM'] = 'powerpc64-unknown-linux-gnu-embedspu'
    elif kw['target'] == 'cell-ps3':
        env['_TOOLCHAINSPUPREFIX'] = 'spu-'
        env['EMBEDSPUCOM'] = 'ppu-embedspu -m32'
    else:
        assert False
    env['CPPFLAGS'] = [
        '-x', 'c++',
        '-Wall',
        '-g',
    ]
    if kw['configuration'] == 'debug':
        env['CPPFLAGS'] += [
            '-O0',
        ]
    else:
        env['CPPFLAGS'] += [
            '-O3',
        ]

    env.Append(**kw)

    env['BUILDERS']['StripElf'] = Builder(
        action = [
            '${_TOOLCHAINSPUPREFIX}strip ${SOURCE} -o ${TARGET}',
            '${_TOOLCHAINSPUPREFIX}objcopy --add-gnu-debuglink=${SOURCE} ${TARGET}',
        ],
        suffix = '.strip',
        src_suffix = '',
    )
    return env

def addEmbedBuilder(env):
    def getHeaderStub(name):
        result = \
'''#ifndef %(guard)s
#define %(guard)s

#include <libspe2.h>

extern spe_program_handle_t %(name)s;

#endif // %(guard)s
''' % {'name': name, 'guard': '__EMBED__%s__H__' % name.upper()}
        return result.replace('\n', '\\n')

    env['_getHeaderStub'] = getHeaderStub

    def embedEmitter(target, source, env):
        assert len(source) == 1, 'Builder accepts only one source'
        assert len(target) == 1, 'You must specify only one target'
        path, ext = os.path.splitext(str(target[0]))
        if not ext:
            ext = '.eo'
        name = os.path.basename(path)
        return ([path + ext, 'symbols.h'], [env.Value('%s_main' % name), source[0]])

    env['BUILDERS']['EmbedElf'] = Builder(
        action = [
            '${EMBEDSPUCOM} ${SOURCES[0]} ${SOURCES[1]} ${TARGETS[0]}',
            'echo -e -n "${_getHeaderStub(SOURCES[0].get_contents())}" > ${TARGETS[1]}',
        ],
        emitter = embedEmitter,
    )
